package com.example.toolproject.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.domain.LabReport;
import com.example.toolproject.demo.domain.User;
import com.example.toolproject.demo.service.LabReportService;
import com.example.toolproject.demo.util.ResultBean;
import com.example.toolproject.demo.util.excel.ExcelUtils;
import com.example.toolproject.demo.util.jwt.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

/**
 * @ClassName LabReportController
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-06-30 11:09
 **/
@Controller
@CrossOrigin
@RequestMapping("/labReport")
public class LabReportController {

    @Autowired
    private LabReportService labReportService;

    private Logger logger = LoggerFactory.getLogger(LabReportController.class);

    @Autowired
    private ExcelUtils excelUtils;

    /**
     * 执行插入实验报告操作
     *
     * @param labReport 实验报告实体
     * @param request
     * @return
     */
    @PostMapping("/insertLabReport")
    @ResponseBody
    public ResultBean insertLabReport(@RequestBody LabReport labReport, HttpServletRequest request) {
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        /**
         * 获取用户id
         */
        int userId = u.getId();
        //设置用户id
        labReport.setUserId(userId);
        labReport.setLabDate(new Date());
        //执行插入用户实验报告
        try {
            labReportService.insertReport(labReport);
            return ResultBean.success("执行添加实验报告成功");
        } catch (Exception e) {
            logger.error("用户：" + userId + " 添加实验报告失败");
            e.printStackTrace();
            return ResultBean.error("执行添加实验报告失败");
        }
    }


    /**
     * 获取所有实验报告
     *
     * @param request
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getAllLabReport")
    @ResponseBody
    public ResultBean getAllLabReport(HttpServletRequest request, Integer pageNum, Integer pageSize) {
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
            pageSize = 10;
        }
        /**
         * 执行分页
         */
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<LabReport> reportList = null;
            /**
             * 判断用户身份
             */
            //即管理员用户
            if (u.getRoleId().equals(1)) {
                reportList = labReportService.getAllLabReportByUserId(null);
                if(StringUtils.isEmpty(reportList) || reportList.size()==0){
                    return ResultBean.error("没有试验报告信息");
                }
            } else if (u.getRoleId().equals(2)) {
                //即教师身份
                reportList = labReportService.getAllLabReportByUserId(null);
                if(StringUtils.isEmpty(reportList) || reportList.size()==0){
                    return ResultBean.error("没有试验报告信息");
                }
            } else {
                reportList = labReportService.getAllLabReportByUserId(u.getId());
                if(StringUtils.isEmpty(reportList) || reportList.size()==0){
                    return ResultBean.error("学生没有提交实验报告信息");
                }
            }
            PageInfo<LabReport> pageInfo = new PageInfo<LabReport>(reportList);
            return ResultBean.success("获取到用户实验报告数据", pageInfo);
        } catch (Exception e) {
            return ResultBean.error("没有获取到实验报告信息");
        }
    }


    /**
     * 根据实验报告id获取实验报告信息
     *
     * @param request
     * @param labReportId
     * @return
     */
    @GetMapping("/getLabReportById")
    @ResponseBody
    public ResultBean getLabReportById(HttpServletRequest request, long labReportId) {
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        /**
         * 执行查询操作
         */
        try {
            LabReport labReport = labReportService.getLabReportById(labReportId);
            return ResultBean.success("查询实验报告成功", labReport);
        } catch (Exception e) {
            return ResultBean.error("查询实验报告失败");
        }
    }


    /**
     * 根据实验报告id删除实验报告
     *
     * @param request
     * @param data    json字符串
     * @return
     */
    @PostMapping("/deleteLabReport")
    @ResponseBody
    public ResultBean deleteLabReport(HttpServletRequest request, @RequestBody String data) {
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        /**
         * 解析json字符串
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        //获取传输的实验报告id
        long labReportId = jsonObject.getLongValue("labReportId");
        try {
            /**
             * 执行删除操作
             */
            labReportService.deleteLabReport(labReportId);
            return ResultBean.success("实验报告删除成功");
        } catch (Exception e) {
            return ResultBean.error("实验报告删除失败");
        }
    }


    /**
     * 搜索实验报告信息
     * @param request
     * @param pageNum
     * @param pageSize
     * @param message
     * @return
     */
    @GetMapping("/getLabReportByMessage")
    @ResponseBody
    public ResultBean getLabReportByMessage(HttpServletRequest request,Integer pageNum,Integer pageSize,String message){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
            pageSize = 10;
        }
        /**
         * 执行分页
         */
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<LabReport> reportList = null;
            /**
             * 判断用户身份
             */
            //即管理员用户
            if (u.getRoleId().equals(1)) {
                reportList = labReportService.getLabReportByMessage(null,message);
                if(StringUtils.isEmpty(reportList) || reportList.size()==0){
                    return ResultBean.error("没有试验报告信息");
                }
            } else if (u.getRoleId().equals(2)) {
                //即教师身份
                reportList = labReportService.getLabReportByMessage(null,message);
                if(StringUtils.isEmpty(reportList) || reportList.size()==0){
                    return ResultBean.error("没有试验报告信息");
                }
            } else {
                reportList = labReportService.getLabReportByMessage(u.getId(),message);
                if(StringUtils.isEmpty(reportList) || reportList.size()==0){
                    return ResultBean.error("学生没有提交实验报告信息");
                }
            }
            PageInfo<LabReport> pageInfo = new PageInfo<LabReport>(reportList);
            return ResultBean.success("获取到用户实验报告数据", pageInfo);
        } catch (Exception e) {
            return ResultBean.error("没有获取到实验报告信息");
        }
    }


    /**
     * 导出实验报告内容
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response,String token){
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        try {
            List<LabReport> reportList = null;
            /**
             * 判断用户身份
             */
            //即管理员用户
            if (u.getRoleId().equals(1)) {
                reportList = labReportService.getLabReportByMessage(null,null);
            } else if (u.getRoleId().equals(2)) {
                //即教师身份
                reportList = labReportService.getLabReportByMessage(null,null);
            } else {
                reportList = labReportService.getLabReportByMessage(u.getId(),null);
            }
            excelUtils.cooperationData(request,response,reportList,"用户实验报告数据",LabReport.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}